package com.b.service.impl;

import com.b.domain.Category;
import com.b.repository.CategoryRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import com.b.dao.CategoryMapper;
import com.b.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class CategoryServiceImpl implements CategoryService{

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private CategoryRepository categoryRepository;

    @Override
    @Transactional
    public boolean deleteByPrimaryKey(Integer id) {
        try {
            categoryRepository.deleteById(id);
            categoryMapper.deleteByPrimaryKey(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public int insert(Category record) {
        return categoryMapper.insert(record);
    }

    @Override
    public int insertSelective(Category record) {
        return categoryMapper.insertSelective(record);
    }

    @Override
    public Category selectByPrimaryKey(Integer id) {
        return categoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Category record) {
        return categoryMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Category record) {
        return categoryMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Category> getAll() {
        return categoryMapper.getAll();
    }
    @Override
    public SearchPage<Category> list(String type, PageRequest pageRequest) {
        return categoryRepository.findCategoriesByTypeLike(type, pageRequest);
    }
    @Override
    @Transactional
    public boolean add(Category Category) {
        try {
            //先保存到数据库
            categoryMapper.insert(Category);
            //再保存到es
            categoryRepository.save(Category);
            return true;

        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean update(Category Category) {
        try {
            //先更新数据库
            categoryMapper.updateByPrimaryKey(Category);
            //再更新es
            categoryRepository.save(Category);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
